package org.xtense.rcp.util;

import java.util.Date;
import java.util.List;

import org.xtense.engine.IXmlReader;
import org.xtense.log.iLog;
import org.xtense.model.CAttribute;
import org.xtense.model.CDocument;
import org.xtense.model.CElement;
import org.xtense.model.CText;
import org.xtense.model.PathEntry;
import org.xtense.rcp.editors.util.XmlEntry;
import org.xtense.util.StringUtil;

public class XmlEditorReader implements IXmlReader {
	private XmlEntry rootEntry;
	private CDocument doc;
	private String docName;
	private int elementPreGen = 1;
		
	/**
	 * @param docName
	 * @param rootEntry
	 */
	public XmlEditorReader(XmlEntry rootEntry, String docName) {
		this.rootEntry = rootEntry;
		if(docName!= null) {
			this.docName = docName;
		} else {
			this.docName = StringUtil.append(new Object[]{new Date().getTime(),".xml"});
		}
	}

	public CDocument read() {
		iLog.info("Reading from the editor...");
		doc = new CDocument(docName);
		//only the root
		goThroughElements(rootEntry, 0);
		iLog.info("Finish reading.");
		return doc;
	}

	private void goThroughElements(XmlEntry entry,int pre) {
		if (entry.getType() == XmlEntry.Element) {
			CElement cElement = new CElement(elementPreGen++, entry.getName(),
					pre);
			doc.addElement(cElement);
			
			//change delimiter of xpath here
			doc.addPath(new PathEntry(cElement.getElementPre(), StringUtil.changeDelimiter(entry.getPath())));
			
			// If current element contains text
			if (entry.getValue().length() != 0) {
				CText cText = new CText(cElement.getElementPre(), entry.getValue());
				doc.addText(cText);
			}
			//children
			List<ITreeEntry> child = entry.getChildren();
			for(ITreeEntry e:child) {
				XmlEntry xmle = (XmlEntry)e;
				goThroughElements(xmle,cElement.getElementPre());
			}
		} else if(entry.getType() == XmlEntry.Attribute) {
			CAttribute cAttribute = new CAttribute(pre,entry.getName(),entry.getValue());
			doc.addAttribute(cAttribute);
		}

	}

}
